package com.xinshujia.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinshujia.dao.QuartzDao;
import com.xinshujia.entity.DeviceEntity;
import com.xinshujia.entity.QuartzEntity;
import com.xinshujia.service.DeviceService;
import com.xinshujia.service.QuartzService;
import com.xinshujia.utils.QuartzUtil;
import com.xinshujia.utils.StatusConstants;
import org.quartz.Scheduler;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * *************************************
 * *   @author: 野狼上校               **
 * *   @since: 2024-07-20 17:13       **
 * *   @version: 1.0                  **
 * *************************************
 * <p>
 * 定时任务实现类
 */
@Service
public class QuartzServiceImpl extends ServiceImpl<QuartzDao, QuartzEntity> implements QuartzService {
    private final QuartzDao quartzDao;
    private final Scheduler scheduler;
    private final DeviceService deviceService;

    public QuartzServiceImpl(QuartzDao quartzDao, Scheduler scheduler, DeviceService deviceService) {
        this.quartzDao = quartzDao;
        this.scheduler = scheduler;
        this.deviceService = deviceService;
    }

    /**
     * 查询是否存在该设备的定时任务
     */
    @Override
    public QuartzEntity findQuartzByDeviceGuid(String deviceGuid) {
        if (StringUtils.hasLength(deviceGuid)) {
            return quartzDao.findQuartzByDeviceGuid(deviceGuid);
        }
        return null;
    }

    /**
     * 定时任务
     *
     * @param deviceGuid  设备Id
     * @param operateType 操作类型 （0：停止，1：运行）
     */
    @Transactional
    @Override
    public Boolean quartzOperate(String deviceGuid, Integer operateType) {
        boolean flag = false;
        QuartzEntity quartzEntity = findQuartzByDeviceGuid(deviceGuid);
        DeviceEntity deviceEntity = deviceService.findDeviceByDeviceGuid(deviceGuid);
        if (ObjectUtils.isEmpty(deviceEntity)) {
            return false;
        }

        if (operateType == 0) {
            // 暂停
            if (!ObjectUtils.isEmpty(quartzEntity)) {
                boolean pauseFlag = QuartzUtil.pauseScheduleJob(scheduler, deviceGuid);
                if (pauseFlag) {
                    // 更新定时任务表和设备表中的定时任务运行状态
                    flag = updateQuartzStatus(quartzEntity, deviceEntity);
                }
                return flag;
            }
        } else if (operateType == 1) {
            // 启动
            boolean deleteFlag = QuartzUtil.deleteScheduleJob(scheduler,deviceGuid);
            //删除表中的数据
            if(!ObjectUtils.isEmpty(quartzEntity)){
                quartzDao.deleteByDeviceGuid(deviceGuid);
            }
            if (deleteFlag) {
                // 创建定时任务并启动，同时更新定时任务表和设备表中的定时任务运行状态
                flag = createQuartzTaskJob(deviceGuid, deviceEntity);
            }
        }
        return flag;
    }

    /**
     * 创建定时任务并启动，同时更新定时任务表和设备表中的定时任务运行状态
     */
    private boolean createQuartzTaskJob(String deviceGuid, DeviceEntity deviceEntity) {
        //创建
        QuartzEntity quartzEntity1 = new QuartzEntity();
        quartzEntity1.setJobStatus(StatusConstants.DEVICE_RUN);
        quartzEntity1.setJobName(deviceGuid);
        quartzEntity1.setJobClass("com.xinshujia.task.DeviceQuartzTask");
        quartzEntity1.setCronExpression("*/1 * * * * ?");
        boolean createFlag = QuartzUtil.createScheduleJob(scheduler, quartzEntity1);
        if (createFlag) {
            // 更新定时任务表的定时任务的状态
            int insert = quartzDao.insert(quartzEntity1);
            // 更新设备表中的运行状态
            deviceEntity.setDeviceRunStatus(StatusConstants.DEVICE_RUN);
            boolean saveOrUpdate = deviceService.saveOrUpdate(deviceEntity);
            return saveOrUpdate && insert > 0;
        }
        return false;
    }

    /**
     * 更新定时任务表和设备表中的定时任务运行状态
     */
    private boolean updateQuartzStatus(QuartzEntity quartzEntity, DeviceEntity deviceEntity) {
        // 更新定时任务表中的运行状态
        quartzEntity.setJobStatus(StatusConstants.DEVICE_STOP);
        int updateCount = quartzDao.updateById(quartzEntity);
        // 更新设备表中的运行状态
        deviceEntity.setDeviceRunStatus(StatusConstants.DEVICE_STOP);
        boolean saveOrUpdate = deviceService.saveOrUpdate(deviceEntity);
        return saveOrUpdate && updateCount > 0;
    }
}
